<?php

/*------------------------------------------------------------------------
# com_invoices - Invoices for Joomla
# ------------------------------------------------------------------------
# author				Germinal Camps
# copyright 			Copyright (C) 2012 JoomlaFinances.com. All Rights Reserved.
# @license				http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: 			http://www.JoomlaFinances.com
# Technical Support:	Forum - http://www.JoomlaFinances.com/forum
-------------------------------------------------------------------------*/

//no direct access
defined('_JEXEC') or die('Restricted access.');



jimport('joomla.application.component.model');

class InvoicesModelInvoice extends JModelLegacy
{
	  
	function __construct()
	{
		parent::__construct();

		$id = JRequest::getVar('id');
		$this->setId((int)$id);
				
	}


	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
		
	}
	
	function &getData()
	{
		
		// Load the data
		
		$query = 	' SELECT i.* '.
					' FROM #__invoices_invoices as i '.
					' WHERE i.id = ' . $this->_id
					;
		$this->_db->setQuery( $query );
		$this->_data = $this->_db->loadObject();
		
		//$this->_data->taxes = explode(",", $this->_data->taxes );

		return $this->_data;
	}
	
	function &getTemplate()
	{
		
		$query = 	' SELECT te.* '.
					' FROM #__invoices_templates as te '.
					' WHERE te.id = ' . $this->_data->template_id
					;
		$this->_db->setQuery( $query );
		$this->template = $this->_db->loadObject();
			
		return $this->template;
	}
	
	function &getItems()
	{
		
		$query = 	' SELECT it.* '.
					' FROM #__invoices_items as it'.
					' WHERE it.invoice_id = ' . $this->_data->id.
					' ORDER BY ordering '
					;
		$this->_db->setQuery( $query );
		$this->items = $this->_db->loadObjectList();
			
		return $this->items;
	}
	
	function &getPayments()
	{
		
		$query = 	' SELECT pa.* '.
					' FROM #__invoices_payments as pa '.
					' WHERE pa.invoice_id = ' . $this->_data->id .
					' AND pa.payment_status = 1 '.
					' ORDER BY ordering '
					;
		$this->_db->setQuery( $query );
		$this->payments = $this->_db->loadObjectList();
			
		return $this->payments;
	}

	function &getPayments2()
	{
		
		$query = 	' SELECT pa.* '.
					' FROM #__invoices_payments as pa '.
					' WHERE pa.invoice_id = ' . $this->_data->id .
					' AND pa.payment_status = 0 '.
					' ORDER BY ordering '
					;
		$this->_db->setQuery( $query );
		$this->payments2 = $this->_db->loadObjectList();
			
		return $this->payments2;
	}
	
	function &getTaxes()
	{
		if($this->_data->taxes){
			$query = 	' SELECT * '.
						' FROM #__invoices_taxes '.
						' WHERE id IN ('.$this->_data->taxes.') '.
						' ORDER BY ordering, name '
						;
			$this->_db->setQuery( $query );
			$this->taxes = $this->_db->loadObjectList();
		}
		return $this->taxes;
	}
	
	function store()
	{	
		$row =& $this->getTable();

		$data = JRequest::get( 'post' );
		
		// Bind the form fields to the album table
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->store()) {
			
			$this->setError( $this->_db->getErrorMsg() );
			return false;
		}
		//print_r($row);die();
		
		if(!$data["id"]){ // it's a new item
			$data["id"] = $row->id;
		}
			
		return true;
	}
	
	function delete()
	{
		$id = JRequest::getInt( 'id' );

		$row =& $this->getTable();
		
		if ( $id ) {
			
			if (!$row->delete( $id )) {
				$this->setError( $this->_db->getErrorMsg() );
				return false;
			}
			
		}
		
		return true;
	}
	
	function sendMail(){
		$data = $this->getData();
		
		$params = JComponentHelper::getParams( 'com_invoices' );
		
		$from = $params->get('email_email') ;
		$from_name = $params->get('email_name') ;
		$subject = $params->get('email_subject') ;
		$subject = str_replace("{invoice_num}", $data->invoice_num, $subject) ;

		$view		= $this->getInvoiceView();
		
		$view->invoice		= $data;
		$view->template		= $this->getTemplate();
		$view->items		= $this->getItems();
		$view->taxes		= $this->getTaxes();
		$view->payments		= $this->getPayments();
		$view->payments2		= $this->getPayments2();
		$view->params		= $params;
		
		if($view->template->content_pdf) $view->template->content = $view->template->content_pdf ;
		
		$view->_path['template'][1] = JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'invoice'.DS.'tmpl' ;
		
		$plantilla = 'email' ;
		
		$message = $view->loadTemplate( $plantilla );
		
		$styles = "<style>".$view->template->styles."</style>" ;
		$message = $styles . $message ;
		
		$to = $data->to_email;

		$mail = JFactory::getMailer();
		$mail->addRecipient($to);
		$mail->setsender(array($from, $from_name));
		$mail->setSubject($subject);
		$mail->setbody($message);
		$mail->isHTML(true);
		
		if($params->get('pdfemail') && InvoicesHelper::PDFavailable()){
			//create PDF
			$viewpdf		= $this->getInvoiceView('dompdf');
			
			$viewpdf->invoice		= $view->invoice	;
			$viewpdf->template		= $view->template;
			$viewpdf->items			= $view->items	;
			$viewpdf->taxes			= $view->taxes	;
			$viewpdf->payments		= $view->payments;
			$viewpdf->payments2		= $view->payments2;
			$viewpdf->params		= $params;

			if($viewpdf->invoice->invoice_num) $pdfname = $viewpdf->invoice->invoice_num;
			else $pdfname = rand();
			
			$location = JPATH_SITE.DS.$params->get('pdffolder','pdfinvoices').DS.$pdfname . ".pdf" ;
			$pdf = $viewpdf->storepdf($location);

			if($pdf) $mail->addAttachment($location, $viewpdf->invoice->invoice_num . ".pdf") ; 

		}

		$sent = $mail->Send();
		return $sent ;
		//return $mail->sendMail($from, $from_name, $to, $subject, $message, true ); // true is for HTML
		
	}
	
	function getInvoiceView($type = "html")
	{
		if (!class_exists( 'InvoicesViewInvoice' ))
		{
			// Build the path to the model based upon a supplied base path
			$path = JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'invoice'.DS.'view.'.$type.'.php';
			$false = false;

			// If the model file exists include it and try to instantiate the object
			if (file_exists( $path )) {
				require_once( $path );
				if (!class_exists( 'InvoicesViewInvoice' )) {
					JError::raiseWarning( 0, 'View class InvoicesViewInvoice not found in file.' );
					return $false;
				}
			} else {
				JError::raiseWarning( 0, 'View InvoicesViewInvoice not supported. File not found.' );
				return $false;
			}
		}

		$view = new InvoicesViewInvoice();
		return $view;
	}
	
}